<?php
$dbname="172.16.250.169/orcl";
$dbuser="libsys";
$dbpassword="libsys";

$campusapp_url="https://eaiapp.ccom.edu.cn";
$campusapp_appid="200200405134542698";
$campusapp_appsecret="smeyasjgy1tksxm9bmpv5gnhjbaf6ngu";

function _process_orcale_asciistr($str) {
        return preg_replace_callback(
                '|\\\([0-9A-F]{4})|',
                function ($matches) {
                        return mb_convert_encoding('&#'.intval('0x'.$matches[1],0).';', 'UTF-8', 'HTML-ENTITIES');
                },
                $str);
}

function computeNextOpenDay($date, $location) {
	global $dbname, $dbuser, $dbpassword;
	$weekdays=['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];

	if(get_class($date)=='DateTime') $d=$date;
	else $d=date_create_from_format('Y-m-d', $date);
	try {
		$dbh = new PDO("oci:dbname=//".$dbname.";charset=AL32UTF8", $dbuser, $dbpassword);
		$sql_open_time="SELECT COUNT(*) from OPEN_TIME WHERE ".
"trim(MORN_OPEN_TIME)||trim(MORN_CLOSE_TIME)||trim(AFTN_OPEN_TIME)||trim(AFTN_CLOSE_TIME)||trim(EVEN_OPEN_TIME)||trim(EVEN_CLOSE_TIME)".
"<>'00:0000:0000:0000:0000:0000:00' AND WEEK=:WEEKDAY AND LOCATION='".$location."'";
		$sth_open_time=$dbh->prepare($sql_open_time);

		$sql_close_day="SELECT CLOSE_END_DAY, EXT_DAYS FROM CLOSE_DAY WHERE CLOSE_BGN_DAY<=:NORM_RET_DATE AND CLOSE_END_DAY>=:NORM_RET_DATE AND LOCATION='".$location."'";
		$sth_close_day=$dbh->prepare($sql_close_day);

		do {
			$weekday=$weekdays[intval($d->format('w'))];
			$sth_open_time->execute([':WEEKDAY'=>$weekday]);
			$r=$sth_open_time->fetchColumn();
			if(intval($r)==0) {
				$d->add(new DateInterval('P1D'));
				continue;
			}

			$sth_close_day->execute([':NORM_RET_DATE'=>$d->format('Y-m-d')]);
			$r=$sth_close_day->fetch(PDO::FETCH_ASSOC);
			if(!empty($r)) {
				$d=date_create_from_format('Y-m-d', $r['CLOSE_END_DAY']);
				$d->add(new DateInterval('P'.$r['EXT_DAYS'].'D'));
				continue;
			}

			break;
		} while(TRUE);
	} catch (PDOException $e) {
		throw $e;
	} finally {
		$dbh=null;
	}
	return $d;
}

header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
header("Pragma: no-cache");

if($_SERVER['REQUEST_METHOD']=='GET') {
	if(!array_key_exists('code', $_GET)) $should_redirect=1;
	else {
		$url=sprintf("%s/api/third/get-token", $campusapp_url);
		$opts=['appid'=>$campusapp_appid, 'appsecret'=>$campusapp_appsecret];
		$ch = curl_init($url.'?'.http_build_query($opts));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		$r=curl_exec($ch);
		$result=json_decode($r);
		if($r===FALSE || $result->e || empty($result->d->access_token)) {
			http_response_code(500); exit;
		}
		curl_close($ch);

		$url=sprintf("%s/uc/api/oauth/user-by-code", $campusapp_url);
		$opts=['code'=>$_GET['code'], 'access_token'=>$result->d->access_token];
		$ch = curl_init($url.'?'.http_build_query($opts));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		$r=curl_exec($ch);
		$result=json_decode($r);
		if($r===FALSE || $result->e || empty($result->d->role->number)) {
			$should_redirect=1;
		} else {
			curl_close($ch);
			$uid=$result->d->role->number;
			$uname=$result->d->realname;
		}
	}

	if($should_redirect==1) {
		$url=sprintf('Location: %s/uc/api/oauth/index?redirect=%s&appid=%s',
			$campusapp_url,
			urlencode(sprintf('%s://%s%s',$_SERVER['HTTPS']?'https':'http',$_SERVER['HTTP_HOST'],$_SERVER['REQUEST_URI'])),
			$campusapp_appid
		);
        	header($url, TRUE, 302);
	        exit;
	}
}

?>
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0,viewport-fit=cover">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Expires" content="0" />
    <title>续借图书</title>
    <script src="//cdn.bootcss.com/jquery/3.5.0/jquery.min.js"></script>
<?php
if(preg_match('/wxwork\//', $_SERVER['HTTP_USER_AGENT'])) {
?>
    <link rel="stylesheet" href="//res.wx.qq.com/open/libs/weui/1.1.4/weui-for-work.min.css"/>
<?php
} else {
?>
    <link rel="stylesheet" href="//res.wx.qq.com/open/libs/weui/2.3.0/weui.min.css"/>
<?php
}
?>
</head>
<body ontouchstart>
<div class="container" id="container">
<div class="page icons">
<?php
try {
	$dbh = new PDO("oci:dbname=//".$dbname.";charset=AL32UTF8", $dbuser, $dbpassword);
if($_SERVER['REQUEST_METHOD']=='POST') {
	$sql="SELECT location_lst.location, location_lst.LOCATION_NAME, INDI_ACCT.MARC_REC_NO, ASCIISTR(MARC.M_TITLE) AS M_TITLE FROM INDI_ACCT ".
"INNER JOIN LOCATION_LST ON indi_acct.location=location_lst.location ".
"INNER JOIN MARC ON MARC.MARC_REC_NO=INDI_ACCT.MARC_REC_NO WHERE indi_acct.prop_no=:PROP_NO";
	$sth=$dbh->prepare($sql);

	$sql_renew="call LT_RENEWBOOK(:PROP_NO, :CERT_ID, :NORM_RET_DATE, 'MWEI', '500002')";
	$sth_renew=$dbh->prepare($sql_renew);

	$sql_log="call XT_LOG_DETL('41003', 'MWEI', :HOST, '', :MARC_REC_NO, :PROP_NO, :CERT_ID, :LOCATION, :NORM_RET_DATE, '')";
	$sth_log=$dbh->prepare($sql_log);

	$titles=[];
        foreach($_POST['prop_no'] as $prop_no) {
		$a=$sth->execute([':PROP_NO'=>$prop_no]);
		$r=$sth->fetch(PDO::FETCH_ASSOC);
		$params=[':PROP_NO'=>$prop_no, ':CERT_ID'=>$_POST['cert_id'], ':NORM_RET_DATE'=>$_POST['renew'.$prop_no]];
		$sth_renew->execute($params);
		$params[':LOCATION']=$r['LOCATION_NAME'];
		$params[':MARC_REC_NO']=$r['MARC_REC_NO'];
		$params[':HOST']=$_SERVER['REMOTE_ADDR'];
		$sth_log->execute($params);
		$titles[]=preg_replace('/[ ]*\/$/', '', trim(_process_orcale_asciistr($r['M_TITLE'])));
	}
	if(count($titles)>0) {
?>
        <div class="page msg_success js_show">
        <div class="weui-msg">
                <div class="weui-msg__icon-area"><i class="weui-icon-success weui-icon_msg"></i></div>
                <div class="weui-msg__text-area"><h2 class="weui-msg__title">续借 <?php echo count($titles); ?> 册成功</h2><p class="weui-msg__desc"><?php echo implode('<br/>', $titles); ?></p></div>
        </div>
        </div>
        <div class="weui-btn-area">
            <a class="weui-btn weui-btn_primary" href="<?php echo sprintf('%s',$_SERVER['PHP_SELF']); ?>">确定返回</a>
        </div>
<?php
	}
} else {
	$sql_temp=
"SELECT lend_lst.cert_id, reader_cert.redr_cert_id, reader.name, lend_lst.PROP_NO, LEND_LST.NORM_RET_DATE, LEND_LST.RENEW_TIMES, INDI_ACCT.LOCATION, ".
"CIRC_RULE.TIME_UNIT, CIRC_RULE.RENEW_YSNO, CIRC_RULE.MAX_RENEW_TIMES, CIRC_RULE.RENEW_BEF_EXP_DAYS, CIRC_RULE.FST_RENEW_DAYS, CIRC_RULE.ADD_RENEW_DAYS, ".
"marc.marc_rec_no, ASCIISTR(MARC.M_TITLE) AS M_TITLE, ASCIISTR(MARC.M_AUTHOR) AS M_AUTHOR, READER.REDR_FLAG, READER_CERT.END_DATE, READER_CERT.CERT_FLAG, ".
"READER_TYPE.CHK_VALIDITY_PERIOD, ".
"CASE WHEN exists(SELECT * FROM PREG_LST WHERE PREG_LST.PREG_END_DATE>='%s' AND PREG_LST.PREG_FLAG=0 AND PREG_LST.CALL_NO=INDI_ACCT.CALL_NO ) ".
"then '1' else '0' end AS HAS_VALID_PREG ".
"FROM LIBSYS.LEND_LST ".
"inner join LIBSYS.circ_rule on lend_lst.rule_no_f=circ_rule.rule_no ".
"inner join libsys.reader on lend_lst.cert_id=reader.cert_id ".
"inner join libsys.reader_cert on lend_lst.cert_id=reader_cert.cert_id ".
"inner join libsys.indi_acct on lend_lst.prop_no=indi_acct.prop_no ".
"inner join libsys.marc on indi_acct.marc_rec_no=marc.marc_rec_no ".
"inner join libsys.reader_type on reader.REDR_TYPE_CODE=reader_type.REDR_TYPE_CODE ".
"WHERE reader_cert.redr_cert_id='%s' AND reader.name='%s' ORDER BY NORM_RET_DATE ASC, PROP_NO ASC";
	$sql=sprintf($sql_temp, date('Y-m-d'), $uid, $uname);
	$results=$dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
	if (count($results)>0) {
?>
	<form id="renewForm" method="post" action="<?php echo sprintf('%s',$_SERVER['PHP_SELF']); ?>">
	<input type="hidden" name="cert_id" value="<?php echo $results[0]['CERT_ID']; ?>"/>
        <div class="weui-cells__title"><?php echo sprintf("%s (%s) ",$uname, $uid); ?>当前在借</div>
        <div class="weui-cells weui-cells_checkbox">
        <?php
        foreach ($results as $item) {
                $item['M_TITLE']=trim(_process_orcale_asciistr($item['M_TITLE']));
                $item['M_TITLE']=preg_replace('/[ ]*\/$/', '', $item['M_TITLE']);
                $item['M_AUTHOR']=trim(_process_orcale_asciistr($item['M_AUTHOR']));
                $item['M_AUTHOR']=preg_replace('/^(\/)/', '', $item['M_AUTHOR']);
                $ret_date=date_create_from_format('Y-m-d', trim($item['NORM_RET_DATE']));
                $can_renew=0; $reason='';
                $interval=date_diff(date_create(), $ret_date);
		if($item['REDR_FLAG']=='0') {
			$reason='不可续借：读者已注销。';
		} else if($item['END_DATE']<date('Y-m-d') && $item['CHK_VALIDITY_PERIOD']=='1') {
			$reason='不可续借：读者证已过期。';
		} else if($item['CERT_FLAG']<>'1') {
			$reason='不可续借：读者证状态异常。';
		} else if($item['RENEW_YSNO']=='0') {
                        $reason='不可续借：本书不可续借。';
		} else if($item['HAS_VALID_PREG']=='1') {
			$reason='不可续借：已有其他读者预约。';
                } else if($item['MAX_RENEW_TIMES']<=$item['RENEW_TIMES']) {
                        $reason='不可续借：续借次数已满。';
                } else if(date_create() > $ret_date) {
                        $reason='不可续借：已超期。';
                } else if(intval($interval->format('%a'))>intval($item['RENEW_BEF_EXP_DAYS'])) {
                        $reason='不可续借：未到续借日期。';
                } else {
                        $can_renew=1;
			$adate=date_add(date_create_from_format('Y-m-d', trim($item['NORM_RET_DATE'])), new DateInterval('P'.($item['MAX_RENEW_TIMES']-$item['RENEW_TIMES']==1?$item['FST_RENEW_DAYS']:$item['ADD_RENEW_DAYS']).'D'));
			$adate=computeNextOpenDay($adate, $item['LOCATION']);
                        $reason=sprintf('可续借至%s。',$adate->format('Y年n月j日'));
			?>
			<input type="hidden" name="renew<?php echo $item['PROP_NO'];?>" value="<?php echo $adate->format('Y-m-d');?>"/>
			<?php
                }
        ?>
            <label class="weui-cell weui-check__label" for="checkbox<?php echo $item['PROP_NO'];?>">
                <div class="weui-cell__hd">
                    <input type="checkbox" class="weui-check" name="prop_no[]" value="<?php echo $item['PROP_NO'];?>" id="checkbox<?php echo $item['PROP_NO'];?>" <?php
if($can_renew==0) echo 'disabled="disabled"';
else echo 'checked="checked"'; ?>/>
                    <i class="weui-icon-checked"></i>
                </div>
                <div class="weui-cell__bd">
                    <p><?php echo sprintf("%s / %s", $item['M_TITLE'], $item['M_AUTHOR']); ?></p>
<ul class="weui-media-box__info">
<li class="weui-media-box__info__meta">应于<?php echo $ret_date->format('Y年n月j日'); ?>归还。</li>
<li class="weui-media-box__info__meta"><?php echo $reason; ?></li>
</ul>
                </div>
            </label>
        <?php
        }
        ?>
	</div>
        <div class="weui-btn-area">
            <a class="weui-btn weui-btn_primary" href="#" id="btnOK">一键续借所选图书</a>
        </div>
	</form>
<script>
$(function() {
  $(".weui-check").change(function() {
    if($(".weui-check:checked").length == 0)
      $(".weui-btn_primary").addClass("weui-btn_disabled");
    else if($(".weui-check:checked").length == 1)
      $(".weui-btn_primary").removeClass("weui-btn_disabled");
  });
  $(".weui-check").change();

  $("#btnOK").click(function() {
    event.preventDefault();
    if($(".weui-check:checked").length > 0) {
      $("#renewForm").submit();
    }
  });
});
</script>
<?php
	} else {
?>
	<div class="page msg_info js_show">
	<div class="weui-msg">
		<div class="weui-msg__icon-area"><i class="weui-icon-info weui-icon_msg"></i></div>
		<div class="weui-msg__text-area"><h2 class="weui-msg__title">无在借</h2><p class="weui-msg__desc"><?php echo sprintf("%s (%s) ",$uname, $uid); ?>无在借图书，无需续借。</p></div>
	</div>
	</div>
<?php
	}
	}

} catch (PDOException $e) {
?>
	<div class="page msg_info js_show">
	<div class="weui-msg">
		<div class="weui-msg__icon-area"><i class="weui-icon-warn weui-icon_msg"></i></div>
		<div class="weui-msg__text-area"><h2 class="weui-msg__title">错误</h2><p class="weui-msg__desc"><?php echo sprintf("%s: %s",$e->getCode(), $e->getMessage()); ?></p></div>
	</div>
	</div>
<?php
} finally {
	$dbh=null;
}
?>
</div>
</div>
</body>
</html>
